package com.shopping.dao.impl;

import com.shopping.dao.CarDao;
import com.shopping.model.Car;
import com.shopping.model.view.CarView;
import com.shopping.utils.DBUtil;

import java.util.List;

public class CarDaoImpl extends DBUtil implements CarDao {
    @Override
    public void addCar(Car car) {
        String sql = "insert into tbl_car values(default,?,?,?)";
        super.executeUpdate(sql,car.getFlower_id(),car.getCar_count(),car.getUserId());
    }

    @Override
    public boolean isContains(int flowerId, int userId) {
        String sql = "select count(car_id) from tbl_car where flower_id=? and userId=?";
        long count = (Long) super.executeQueryNumber(sql,flowerId,userId);
        if (count==0){
            return true;
        }
        return false;
    }

    @Override
    public void updateCount(int flowerId, int userId, int count) {
        String sql = "update tbl_car set car_count=car_count+? where flower_id=? and userId=?";
        super.executeUpdate(sql,count,flowerId,userId);
    }

    @Override
    public void updateCount(int carId, int count) {
        String sql="update tbl_car set car_count=? where car_id=?";
        super.executeUpdate(sql,count,carId);
    }

    @Override
    public void deleteCarById(int carId) {
        String sql = "delete from tbl_car where car_id=?";
        super.executeUpdate(sql,carId);
    }

    @Override
    public void clearCar(int userId) {
        String sql = "delete from tbl_car where userId=?";
        super.executeUpdate(sql,userId);
    }

    @Override
    public int countCar(int userId) {
        String sql = "select count(car_id) from tbl_car where userId=?";
        int count = ((Long)super.executeQueryNumber(sql,userId)).intValue();
        return count;
    }

    @Override
    public Integer getCountByUserIdAndFlowerId(Integer user_id, int flowerId) {
        String sql = "select car_count from tbl_car where userId=? and flower_id=?";
        return (Integer) super.executeQueryNumber(sql,user_id,flowerId);
    }



    @Override
    public List<CarView> queryCar(int userId) {
        String sql = "select " +
                "           car.car_id,flower.flower_id," +
                "           flower.flower_name," +
                "           flower.flower_price," +
                "           car.car_count," +
                "           flower.flower_image," +
                "           flower.flower_price*car.car_count sum_price " +
                "     from " +
                "           tbl_flower flower " +
                "     inner join " +
                "           tbl_car car " +
                "     on " +
                "           flower.flower_id=car.flower_id " +
                "     where " +
                "           car.userId=?";
        return super.executeQueryList(sql,CarView.class,userId);
    }
}